<template>
  <div class="app-container">
    <div class="filter-container">

        <el-select v-model="listQuery.type" filterable placeholder="请选择" class="filter-item"
                   clearable
        >
          <el-option
            v-for="item in typeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      <!--        <el-input v-model="listQuery.title" placeholder="关键字搜索" style="width: 200px;" class="filter-item"  />-->
      <el-button class="filter-item" style="float:right;margin-right:10px" type="primary" @click="handleCreate">
        添加
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width:100%;"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" min-width="80px" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.type ==1" type="success">pc</el-tag>
          <el-tag v-else>wap</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" min-width="80px" align="center">
        <template slot-scope="{row}">
          <el-link type="success">{{ row.sort }}</el-link>
        </template>
      </el-table-column>
      <!--        <el-table-column label="类型" class-name="status-col" min-width="100">-->
      <!--          <template slot-scope="{row}">-->
      <!--           <el-tag  v-if="row.type == 2" size="small">首页轮播图</el-tag>-->
      <!--           <el-tag  v-else size="small">新闻轮播图</el-tag>-->
      <!--          </template>-->
      <!--        </el-table-column>-->
      <el-table-column label="图片" min-width="80px" align="center">
        <template slot-scope="{row}">
          <el-tooltip content="点击放大" placement="right" effect="light">
            <el-image
              style="height:60px"
              :src="row.thumb"
              fit="contain"
              @click="showBanner(row.url)"
            ></el-image>
          </el-tooltip>
        </template>
      </el-table-column>
<!--      <el-table-column label="手机端图" min-width="80px" align="center">-->
<!--        <template slot-scope="{row}">-->
<!--          <el-tooltip content="点击放大" placement="right" effect="light">-->
<!--            <el-image-->
<!--              style="height:60px"-->
<!--              :src="row.wap_thumb"-->
<!--              fit="contain"-->
<!--              @click="showBanner(row.wap_url)"-->
<!--            ></el-image>-->
<!--          </el-tooltip>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="创建时间" class-name="status-col" min-width="100">
        <template slot-scope="{row}">
          <span>{{ row.created_at }}</span>
        </template>
      </el-table-column>
      <!--        <el-table-column label="更新时间" class-name="status-col" min-width="100">-->
      <!--          <template slot-scope="{row}">-->
      <!--            <span>{{ row.updated_at }}</span>-->
      <!--          </template>-->
      <!--        </el-table-column>-->
      <el-table-column label="操作" align="center" min-width="200px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="50%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px"
      >
        <el-form-item label="类型">
          <el-select v-model="temp.type" filterable placeholder="请选择" class="filter-item"
                     clearable
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序">
          <el-input type="number" v-model="temp.sort"></el-input>
        </el-form-item>

        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            action="/api/upload/base_image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <el-image v-if="imageUrl" :src="imageUrl+'?rondom='+ Math.ceil(Math.random()*5)" class="avatar" width="100%"
                      fit="contain"
            ></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="外链">
          <el-input v-model="temp.addr"></el-input>
        </el-form-item>

<!--        <el-form-item label="手机端图片">-->
<!--          <el-upload-->
<!--            class="avatar-uploader"-->
<!--            action="/api/upload/image"-->
<!--            :show-file-list="false"-->
<!--            :on-success="handleAvatarSuccess1"-->
<!--            :before-upload="beforeAvatarUpload"-->
<!--          >-->
<!--            <el-image v-if="imageUrl1" :src="imageUrl1+'?rondom='+ Math.ceil(Math.random()*5)" class="avatar" width="100%"-->
<!--                      fit="contain"-->
<!--            ></el-image>-->
<!--            <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
<!--          </el-upload>-->
<!--        </el-form-item>-->
      </el-form>
      <center>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </center>
    </el-dialog>
    <el-dialog :visible.sync="dialogBannerVisible" width="80%">
      <center>
        <el-image fit="contain" :src="showBannerUrl" width="100%"></el-image>
      </center>
    </el-dialog>
  </div>
</template>

<script>
import { getBannerList, createBanner, deleteBanner } from '@/api/banner'
import Pagination from '@/components/Pagination'

export default {
  name: 'BannerList',
  components: { Pagination },
  data() {
    return {
      content: '',
      imageUrl: '',
      imageUrl1: '',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        type: ''
      },
      dialogFormVisible: false,
      dialogBannerVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      typeList: [
        {
          'id': 1,
          'name': 'pc'
        },
        {
          'id': 2,
          'name': 'wap'
        }
      ],
      showBannerUrl: '',
      temp: {
        id: undefined,
        sort: '',
        url: '',
        thumb: '',
        type: '',
        addr:''
      },
      rules: {
        sort: [{ required: true, message: '排序不能为空' }]
        // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],

      }

    }
  },
  watch: {
    imageUrl: {
      deep: true,
      handler(val) {
      }
    },
    imageUrl1: {
      deep: true,
      handler(val) {
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getBannerList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        // Just to simulate the time of the request
        this.listLoading = false
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        sort: '',
        url: '',
        thumb: '',
        type: '',
        addr:''
      }
      this.imageUrl = ''
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (!this.temp.url || !this.temp.thumb) {
            this.$message.error('请先上传图片')
            return ''
          }
          if (!this.temp.type) {
            this.$message.error('请先选择类型')
            return ''
          }
          createBanner(this.temp).then(response => {
            if (response.code == 200) {
              this.dialogFormVisible = false
              this.$notify({
                message: response.msg,
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.imageUrl = this.temp.thumb
      this.imageUrl1 = this.temp.wap_thumb
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (!this.temp.url || !this.temp.thumb) {
            this.$message.error('请先上传图片')
            return ''
          }
          if (!this.temp.type) {
            this.$message.error('请先选择类型')
            return ''
          }
          const tempData = Object.assign({}, this.temp)
          createBanner(tempData).then(response => {
            if (response.code == 200) {
              this.dialogFormVisible = false
              this.$notify({
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        }
      })
    },

    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        this.imageUrl = res.data.thumb
        this.temp.url = res.data.url
        this.temp.thumb = res.data.thumb
        this.$notify({
          title: '消息',
          type: 'success',
          message: '上传成功',
          duration: 2000
        })
      } else {
        this.$notify({
          title: '消息',
          type: 'error',
          message: '上传失败',
          duration: 2000
        })
      }
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      // const isPNG = file.type === 'image/png'
       const isLt10M = file.size / 1024 / 1024 < 10
      // if (!isJPG && !isPNG) {
      //   this.$message.error('上传图片只能是 JPG/PNG 格式!')
      // }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!')
      }
      return isLt10M
      //  return isJPG && isLt2M;
    },

    handleAvatarSuccess1(res, file) {
      if (res.code == 200) {
        this.imageUrl1 = res.data.thumb
        this.temp.wap_url = res.data.url
        this.temp.wap_thumb = res.data.thumb
        this.$notify({
          title: '消息',
          type: 'success',
          message: '上传成功',
          duration: 2000
        })
      } else {
        this.$notify({
          title: '消息',
          type: 'error',
          message: '上传失败',
          duration: 2000
        })
      }
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    handleDelete(row, index) {
      this.$confirm(
        '确定要删除该条数据吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
        deleteBanner(row.id).then(response => {
          if (response.code == 200) {
            this.list.splice(index, 1)
            this.$notify({
              message: response.msg,
              type: 'success',
              duration: 2000
            })
          }
        })
      }).catch(() => {

      })
    },
    showBanner(url) {
      this.showBannerUrl = url
      this.dialogBannerVisible = true
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
